package com.Smart.smartscals.Activity;

import java.util.HashMap;

import com.Smart.smartscals.Entity.EntityDowload;
import com.Smart.smartscals.Entity.EntityReciveBodyInfo;
import com.Smart.smartscals.Entity.EntityRegist;
import com.Smart.smartscals.Entity.EntityUserInfo;
import com.Smart.smartscals.HttpTools.DownLoadTools;
import com.Smart.smartscals.HttpTools.HttpTools;
import com.Smart.smartscals.HttpTools.ParserJsonTools;
import com.Smart.smartscals.HttpTools.ValidateFormat;
import com.Smart.smartscals.Utils.Const;
import com.Smart.smartscals.Utils.SeletLastDataBaseUtilt;
import com.Smart.smartscals.Utils.SharePreferceTools;
import com.Smart.smartscals.Utils.Tools;
import com.Smart.smartscals.Utils.UserInfoUtils;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

public class ActivityWelcome extends BaseActivity {
	private Handler mHandler;
	private FrameLayout frameLayoutAll;
	private boolean TAG;
	private SmartScalsApplication mApplication;
	private EntityUserInfo userInfoEntity;
	private EntityReciveBodyInfo lastBodyInfoEntity;
	private TextView tvWarm;
	private DownLoadTools mDownLoadTools;
	private EntityDowload mEntityDowload;
	private SharePreferceTools mPreferceTools;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activit_welcome);
		initView();
		initParam();

	}

	private void initParam() {
		mContext = this;
		mPreferceTools = new SharePreferceTools(mContext,
				Const.SHAREPREFERENCENAME);

		// 查询是否存在最后一天记录
		try {
			UserInfoUtils userInfoUtils = new UserInfoUtils(this);
			userInfoEntity = userInfoUtils.getLastUserEntity();

		} catch (Exception e) {
			e.printStackTrace();
		}

		String userName = userInfoEntity.getUserName();
		if (userName != null) {
			TAG = true;
			mApplication = (SmartScalsApplication) getApplication();

			mApplication.setUserName(userName);
			mApplication.setPassword(userInfoEntity.getUserName());
			mApplication.setSex(userInfoEntity.getSex());
			mApplication.setBirthday(userInfoEntity.getBirthday());
			mApplication
					.setHeight(Integer.parseInt(userInfoEntity.getHeight()));
			// 根据userName去查找最后一条bodyInfo,并赋值
			SeletLastDataBaseUtilt lastBodyDataBaseUtils = new SeletLastDataBaseUtilt(
					this);
			lastBodyInfoEntity = lastBodyDataBaseUtils
					.getLastBodyInfoEntity(userName);
			if (lastBodyInfoEntity != null) {
				mApplication.setWeight(lastBodyInfoEntity.getWeight());
				mApplication.setFat(lastBodyInfoEntity.getBodyFat());
				Log.i("mApplication",
						"Weight：" + lastBodyInfoEntity.getWeight() + "Fat:"
								+ lastBodyInfoEntity.getBodyFat());

			}

		} else {
			TAG = false;
		}

		mHandler = new Handler();
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				if (TAG) {
					// 跳转到健康指数界面

				} else {
					// 一定时间后跳转

					if (android.os.Build.VERSION.SDK_INT >= Const.APIVERSIONLIMIT) {

						loginAble();

					} else {
						tvWarm.setVisibility(View.VISIBLE);
					}

				}
			}
		}, Const.GUIDETIME);

	}

	protected void loginAble() {

		EntityRegist loginEntity = new EntityRegist();

		if (mPreferceTools.getString(Const.KEYUSERNAME) != null) {// 第一次使用，没有存储任何用户信息；
			Tools.startActivity(mActivity, mContext,
					com.Smart.smartscals.Activity.ActivityGuide.class);
			return;
		}
		loginEntity.setUserName(mPreferceTools.getString(Const.KEYUSERNAME));
		loginEntity.setPassword(mPreferceTools.getString(Const.KEYPASSWORD));

		// 解析注册过程；
		mEntityDowload = new EntityDowload(this, HttpTools.URLLOGIN,
				HttpTools.REQUESTPOST,
				ValidateFormat.loginDataFormat(loginEntity),
				HttpTools.HTTPAPIHTTPCLIENT, "");

		mDownLoadTools = new DownLoadTools(mEntityDowload);

		new AsyncTask<String, Integer, String>() {

			@Override
			protected String doInBackground(String... params) {

				if (mDownLoadTools.startTration()) {
					return mDownLoadTools.getStrFromNet();
				}
				return null;
			}

			protected void onPostExecute(String result) {

				Tools.setLog("--->registe:" + result);

				if (result != null) {

					// 解析
					HashMap<String, String> map = ParserJsonTools
							.parserLoginJson(result);

					if (map.get("success") != null
							&& map.get("success").equals("true")
							&& map.get("authkey") != null) {

						Tools.setToast(
								mContext,
								mContext.getString(R.string.guide_toast_login_successful));

						saveRelateDate(map);

					} else {

						Tools.setToast(
								// 成功；
								mContext,
								mContext.getString(R.string.guide_toast_login_failed_checksusername));
					}

				} else {
					Tools.setToast(
							mContext,
							mContext.getString(R.string.guide_toast_login_failed_checknetwork));
				}

			};

		}.execute("");

	}

	protected void saveRelateDate(HashMap<String, String> map) {
		// 保存相关的参数；
		mPreferceTools.setString(Const.KEYAUTHKEY, map.get("authkey"));

		Tools.startActivity(mActivity, mContext,
				com.Smart.smartscals.Activity.ActivityMain.class);

	}

	private void initView() {
		frameLayoutAll = (FrameLayout) this
				.findViewById(R.id.activity_welcome_framelayout_all);
		tvWarm = (TextView) this.findViewById(R.id.welcomme_tv_warm);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}
